package team.tunan.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import team.tunan.common.Result;
import team.tunan.entity.User;
import team.tunan.entity.dto.UserDTO;
import team.tunan.service.IUserService;

import javax.servlet.http.HttpSession;

/**
 * @Date 2022/7/6
 * @Author ztc
 * @Description 登录
 */
@Controller
public class LoginController {

    @Autowired
    private IUserService userService;


    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "HELLO";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public Result doLogin(String account, String password, HttpSession session){
        UserDTO user = userService.getUser(account,password);
        System.out.println(user.getUserInfo());
        session.setAttribute("user",user.getUserInfo());
        return new Result(user.isSuccess()?"欢迎"+user.getUserInfo().getUsername()+"登录":"用户名或密码正确，请重试",user.getUserInfo(),user.isSuccess());
    }

    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    @RequestMapping("/doRegister")
    @ResponseBody
    public Result doRegister(User user){
        user.setRole(4);
        int add = userService.add(user);
        if (add>0){
            return new Result("注册成功",null,true);
        }
        return new Result("注册失败，请重试",null,false);
    }



    @RequestMapping("/main")
    public String tomain(HttpSession session){
        System.out.println(session);
        if (session.getAttribute("user")==null){
            return "redirect:/login";
        }
        return "main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session, SessionStatus sessionStatus){
        session.invalidate();
        sessionStatus.setComplete();
        return "redirect:/login";
    }





}
